package controller;

import com.github.pagehelper.PageInfo;
import domain.Permission;
import domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import service.PermissionService;
import service.RoleService;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    //查询所有角色
    @RequestMapping("/all")
    public ModelAndView all(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize){
        ModelAndView modelAndView = new ModelAndView();
        PageInfo<Role> all = roleService.findAll(pageNum, pageSize);
        modelAndView.getModel().put("page",all);
        modelAndView.setViewName("role_all");
        return modelAndView;
    }

    //新增角色
    @RequestMapping("/add")
    public String add(Role role,int[] permission){
        roleService.addRole(role,permission);
        return "redirect:/role/all";
    }

    //
    @RequestMapping("/getAllPermission")
    public ModelAndView getAllPermission(){
        ModelAndView modelAndView = new ModelAndView();
        List<Permission> allPermission = permissionService.findAllPermission();
        modelAndView.setViewName("role_add");
        modelAndView.getModel().put("permissions",allPermission);
        return modelAndView;
    }

    //Role详情
    @RequestMapping("/desc")
    public ModelAndView desc(int id){
        ModelAndView modelAndView = new ModelAndView();
        Role roleById = roleService.findRoleById(id);
        modelAndView.getModel().put("role",roleById);
        modelAndView.setViewName("role_desc");
        return modelAndView;
    }

    //修改前查询信息
    @RequestMapping("/information")
    public ModelAndView information(int id){
        ArrayList<Integer> list = new ArrayList<>();
        ModelAndView modelAndView = new ModelAndView();
        Role roleById = roleService.findRoleById(id);
        for (Permission i:roleById.getPermissions()){
            list.add(i.getId());
        }
        List<Permission> allPermission = permissionService.findAllPermission();
        modelAndView.getModel().put("role",roleById);
        modelAndView.getModel().put("permissionId",list);
        modelAndView.getModel().put("permissions",allPermission);
        modelAndView.setViewName("role_update");
        return modelAndView;
    }

    @RequestMapping("/update")
    public String update(Role role,int[] permission){
        roleService.updateRole(role,permission);
        return "redirect:/role/all";
    }
}
